<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8" />
    <title>快速初始化-显示加载的图片</title>
    <script src="//cdn.jsdelivr.net/npm/phaser@3.11.0/dist/phaser.js"></script>
    <style type="text/css">
        body {
            margin: 0;
        }
    </style>
</head>
<body>

<script type="text/javascript">

	var config = {
		type: Phaser.AUTO,
		width: 800,
		height: 600,
		physics: {
			default: 'arcade',
			arcade: {
				gravity: { y: 0 },
				debug: false
			}
		},
		scene: {
			preload: preload,
			create: create,
			update: update
		}
	};
	//初始化
	var game = new Phaser.Game(config);
	var cursors;
	//预加载图片或者资源
    function preload ()
    {
		this.load.image('sky', './assets/sky.png');
		//此处的money.png一定要是序列帧png
		this.load.image('monkey','./assets/monkey.png');
    }

	//显示预加载的资源或者图片
    function create ()
    {
		this.add.image(400, 300, 'sky');
		
		//比如要在游戏里控制一个猴子
		player = this.physics.add.sprite(100, 250, 'monkey');
		//反弹系数
		player.setBounce(0);
		//游戏画布边间是否反弹
		player.setCollideWorldBounds(true);
		
		
		//本节重点，利用anims绑定键盘的关系，并在update里激活
			//绑定左向按键，激活后，程序执行重复序列帧的第8-15帧。以下同理
		this.anims.create({
			key: 'left',
			frames: this.anims.generateFrameNumbers('monkey', { start: 8, end: 15 }),
			frameRate: 15,
			repeat: -1
		});
		//任何键都没按的情况下，比如说停止
		this.anims.create({
			key: 'turn',
			frames: [ { key: 'monkey', frame: 2 } ],
			frameRate: 20
		});
		this.anims.create({
			key: 'right',
			frames: this.anims.generateFrameNumbers('monkey', { start: 16, end: 23 }),
			frameRate: 15,
			repeat: -1
		});
		this.anims.create({
			key: 'up',
			frames: this.anims.generateFrameNumbers('monkey', { start: 24, end: 31 }),
			frameRate: 15,
			repeat: -1
		});
		this.anims.create({
			key: 'down',
			frames: this.anims.generateFrameNumbers('monkey', { start: 32, end: 39 }),
			frameRate: 15,
			repeat: -1
		});	

	//每帧都要调用的方法
    function update ()
    {
		//激活设置的键绑定关系
		cursors = this.input.keyboard.createCursorKeys();
		if (cursors.left.isDown){
			player.setVelocityX(-160);
			player.anims.play('left', true);
			
		}else if (cursors.right.isDown){
			player.setVelocityX(160);
			player.anims.play('right', true);
		}else if(cursors.up.isDown){
			player.setVelocityY(-160);
			player.anims.play('up', true);
		}else if (cursors.down.isDown){
			player.setVelocityY(160);
			player.anims.play('down', true);
		}else{//任何键都没按的情况下
			player.setVelocityX(0);
			player.setVelocityY(0);
			player.anims.play('turn');
	}

    }

</script>

</body>
</html>